<!-- src/views/lawyer/LawyerInfoEdit.vue -->
<script setup>
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import http from '@/axios'

const emit = defineEmits(['update:visible', 'success'])
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  lawyerData: {
    type: Object,
    default: () => ({}),
    required: true
  },
  detailMode: {
    type: Boolean,
    default: false
  }
})

const formRef = ref()
const loading = ref(false)

// 只包含 LawyerUpdateDTO 中的字段
const form = reactive({
  id: null,
  userId: null,
  licenseNo: '',
  specialty: '',
  yearsOfPractice: null,
  introduction: '',
  serviceArea: ''
})

const rules = {
  licenseNo: [
    { required: true, message: '请输入执业证号', trigger: 'blur' },
    { min: 5, max: 30, message: '长度在5到30个字符', trigger: 'blur' }
  ],
  specialty: [
    { required: true, message: '请输入专业领域', trigger: 'blur' }
  ]
}

// 监听律师数据变化，填充表单
watch(
    () => props.lawyerData,
    (newLawyerData) => {
      console.log('[lawyerData watcher] 律师数据变化:', newLawyerData);

      if (newLawyerData && Object.keys(newLawyerData).length > 0) {
        Object.assign(form, {
          id: newLawyerData.id || null,
          userId: newLawyerData.userId || null,
          licenseNo: newLawyerData.licenseNo || '',
          specialty: newLawyerData.specialty || '',
          yearsOfPractice: newLawyerData.yearsOfPractice !== undefined ? newLawyerData.yearsOfPractice : null,
          introduction: newLawyerData.introduction || '',
          serviceArea: newLawyerData.serviceArea || ''
        })
      } else {
        Object.assign(form, {
          id: null,
          userId: null,
          licenseNo: '',
          specialty: '',
          yearsOfPractice: null,
          introduction: '',
          serviceArea: ''
        })
      }
    },
    { immediate: true, deep: true }
)


const handleClose = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}

const handleSubmit = async () => {
  if (props.detailMode) {
    handleClose()
    return
  }

  try {
    loading.value = true
    await formRef.value.validate()

    // 准备提交的数据
    const submitData = {
      id: form.id,
      userId: form.userId,
      licenseNo: form.licenseNo,
      specialty: form.specialty,
      yearsOfPractice: form.yearsOfPractice !== null ? Number(form.yearsOfPractice) : null,
      introduction: form.introduction,
      serviceArea: form.serviceArea
    }

    console.log('准备提交的数据:', submitData)

    // 确保更新时包含ID字段
    if (submitData.id) {
      // 更新现有律师信息
      try {
        // 直接使用 http 实例调用 API
        const response = await http({
          method: 'post',
          url: '/api/lawyer/update',
          data: submitData,
          headers: {
            'Content-Type': 'application/json'
          }
        })

        console.log('API响应:', response)

        // 检查响应状态
        if (response && (response.code === 200 || response.status === 200 || response.data?.code === 200)) {
          ElMessage.success('律师信息更新成功')
          emit('success')
          handleClose()
        } else if (response && response.data) {
          // 处理嵌套在data中的响应
          if (response.data.code === 200 || response.data.success === true) {
            ElMessage.success('律师信息更新成功')
            emit('success')
            handleClose()
          } else {
            const errorMsg = response.data.message || response.data.msg || '更新失败'
            ElMessage.error(errorMsg)
          }
        } else {
          // 默认成功处理（如果响应结构不符合预期但没有错误）
          ElMessage.success('律师信息更新成功')
          emit('success')
          handleClose()
        }
      } catch (error) {
        console.error('API调用失败:', error)
        // 更详细的错误处理
        if (error.response) {
          // 服务器返回了错误响应
          console.error('服务器错误响应:', error.response)
          const errorMsg = error.response.data?.message || error.response.data?.msg || `服务器错误: ${error.response.status}`
          ElMessage.error(errorMsg || '服务器错误')
        } else if (error.request) {
          // 请求已发出但没有收到响应
          console.error('无响应:', error.request)
          ElMessage.error('网络请求无响应，请检查网络连接')
        } else {
          // 其他错误
          console.error('请求错误:', error.message)
          ElMessage.error('请求发送失败: ' + (error.message || '未知错误'))
        }
      } finally {
        loading.value = false
      }
    } else {
      ElMessage.warning('缺少律师ID，无法更新')
      loading.value = false
    }
  } catch (error) {
    if (error !== 'validate') {
      console.error('保存律师信息失败:', error)
      ElMessage.error('保存失败: ' + (error.message || '未知错误'))
    }
    loading.value = false
  }
}
</script>

<template>
  <el-dialog
      :model-value="visible"
      :title="detailMode ? '律师详情' : form.id ? '编辑律师信息' : '新增律师'"
      width="600px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        v-loading="loading"
        :disabled="detailMode"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="律师ID" prop="id">
            <el-input v-model="form.id" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联用户ID" prop="userId">
            <el-input v-model="form.userId" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="执业证号" prop="licenseNo">
            <el-input v-model="form.licenseNo" :disabled="detailMode" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="专业领域" prop="specialty">
            <el-input v-model="form.specialty" :disabled="detailMode" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="执业年限" prop="yearsOfPractice">
            <el-input v-model.number="form.yearsOfPractice" :disabled="detailMode" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="个人介绍" prop="introduction">
            <el-input
                v-model="form.introduction"
                type="textarea"
                :rows="3"
                :disabled="detailMode"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="服务区域" prop="serviceArea">
            <el-input v-model="form.serviceArea" :disabled="detailMode" clearable />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ detailMode ? '关闭' : '取消' }}</el-button>
        <el-button
            v-if="!detailMode"
            type="primary"
            @click="handleSubmit"
            :loading="loading"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
